package com.greenantmall.home;

import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.PagerAdapter;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ViewFlipper;

import com.avos.avoscloud.AVCloud;
import com.avos.avoscloud.AVException;
import com.avos.avoscloud.AVObject;
import com.avos.avoscloud.AVQuery;
import com.avos.avoscloud.AVRelation;
import com.avos.avoscloud.FindCallback;
import com.avos.avoscloud.FunctionCallback;
import com.greenantmall.R;
import com.greenantmall.jazzyviewpager.JazzyViewPager;
import com.greenantmall.jazzyviewpager.OutlineContainer;
import com.greenantmall.jazzyviewpager.JazzyViewPager.TransitionEffect;
import com.greenantmall.myclass.MyGridView;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

public class ActivityHomePage extends Activity implements OnItemClickListener{

	private JazzyViewPager bannerPager;
	private MyGridView stylesSection;
	private ViewFlipper newGoodsSection;
	private GridView goodsInSeasonSection;
	private ViewFlipper recommendSection;
	private ListView hotSaleSection; 
	private ArrayList<String> urlList;
	private List<TradeStyleInfo> tradeStyleInfoList;
	private DisplayImageOptions options;
	private ImageLoadingListener animateFirstListener = new ImageLoadListener();
	private AVObject myAddr=null;//收货地址
	

	Timer mTimer;
	TimerTask mTask;
	int pageIndex = 1;
	boolean isTaskRun;
	
	int bannersCount =0;
	
	public ActivityHomePage() {
		// TODO Auto-generated constructor stub
	}
	
	
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE); 
        setContentView(R.layout.activity_home_page);    
        urlList =new ArrayList<String>();
        tradeStyleInfoList=new ArrayList<TradeStyleInfo>();
        
        //AVAnalytics.trackAppOpened(getIntent());             
        
        options = new DisplayImageOptions.Builder()
		.showImageOnLoading(R.drawable.ic_stub)
		.showImageForEmptyUri(R.drawable.ic_empty)
		.showImageOnFail(R.drawable.ic_error)
		.cacheInMemory(true)
		.cacheOnDisk(true)
		.considerExifParams(true)
		.displayer(new RoundedBitmapDisplayer(20)).build();
        
        queryCloudPara();      
        
        stylesSection=(MyGridView)findViewById(R.id.gridView1);
        newGoodsSection=(ViewFlipper)findViewById(R.id.viewFlipper1);
        goodsInSeasonSection=(GridView)findViewById(R.id.gridView2);
        recommendSection=(ViewFlipper)findViewById(R.id.viewFlipper2);
        hotSaleSection=(ListView)findViewById(R.id.listView1);  
    }
    
    public void onItemClick(AdapterView<?> parent, View view, int position,
            long id) {
         
     //   Intent intent =new Intent(this,AboutHeroActivty.class);
      //  intent.putExtra("HERO", heros[position]);
       // this.startActivity(intent);
         
    }


	private void queryCloudPara(){
		
		AVQuery<AVObject> query = new AVQuery<AVObject>("Banners");
		query.findInBackground(new FindCallback<AVObject>() {
		    public void done(List<AVObject> list, AVException e) { 
		        if (e == null) {
		            Log.d("锟缴癸拷", "Banners锟斤拷询锟斤拷" + list.size() + " 锟斤拷锟斤拷锟斤拷");
		            bannersCount = list.size();
		            for (AVObject banner : list) {
		            	//FragmentAdapterBanners.addBannersPage(banner.getAVFile("photo").getUrl());
		            	urlList.add(banner.getAVFile("image").getUrl());
		            }
		            setupJazziness(TransitionEffect.Tablet);//锟斤拷始锟斤拷Jazziness锟侥讹拷锟斤拷锟斤拷式
		           // mAdapter.notifyDataSetChanged();
		        } else {
		            Log.d("失锟斤拷", "锟斤拷询锟斤拷锟斤拷: " + e.getMessage());
		        }
		    }
		});
		
		AVQuery<AVObject> querySection = new AVQuery<AVObject>("ServerSection");
		querySection.whereEqualTo("uptown","淮祥园");
		querySection.findInBackground(new FindCallback<AVObject>() {
		    public void done(List<AVObject> list, AVException e) { 
		        if (e == null) {
		            myAddr = list.get(0);
		        } else {
		            Log.d("失锟斤拷", "锟斤拷询锟斤拷锟斤拷: " + e.getMessage());
		        }
		    }
		});
		
		AVQuery<AVObject> styleQuery = new AVQuery<AVObject>("TradeStyle");
		styleQuery.whereEqualTo("sectionNum", 2);
		styleQuery.orderByAscending("showIndex");
		styleQuery.findInBackground(new FindCallback<AVObject>() {
		    public void done(List<AVObject> list, AVException e) {
		        if (e == null) {
		            Log.d("锟缴癸拷", "TradeStyle锟斤拷询锟斤拷" + list.size() + " 锟斤拷锟斤拷锟斤拷");
		            for (AVObject obj : list) {		            	
		            	TradeStyleInfo styleInfo = new TradeStyleInfo(); 		                
		            	styleInfo.setUrl(obj.getAVFile("image").getUrl());//锟斤拷锟酵硷拷锟斤拷锟皆达拷锟絀D 
		                styleInfo.setName(obj.getString("name"));
		                tradeStyleInfoList.add(styleInfo); 
		            }
		            initStytleSectionGrid();
		        } else {
		            Log.d("失锟斤拷", "锟斤拷询锟斤拷锟斤拷: " + e.getMessage());
		        }
		    }
		});
		
		AVQuery<AVObject> itemsQuery = new AVQuery<AVObject>("HomePageItems");
		itemsQuery.whereEqualTo("sectionNum", 1);
		//itemsQuery.include("list");
		itemsQuery.orderByAscending("showIndex");
		itemsQuery.findInBackground(new FindCallback<AVObject>() {
		    public void done(List<AVObject> list, AVException e) {
		        if (e == null) {
		            for (AVObject obj : list) {	
		                 AVRelation<AVObject> relation = obj.getRelation("list");
		                 
		                 /*try {
		                	 List<AVObject> goodsList=relation.getQuery().find();		                	 
		                	 for (AVObject goods : goodsList) {		            	
		 		            //锟斤拷锟酵硷拷锟斤拷锟皆达拷锟絀D 
		 		            	ImageLoader.getInstance().displayImage(goods.getAVFile("image").getUrl(),
		 		            			iv, options, animateFirstListener);
		 		            }	              	 
		                	 
						} catch (AVException e1) {
							// TODO Auto-generated catch block
							e1.printStackTrace();
						}*/
		                 relation.getQuery().findInBackground(new FindCallback<AVObject>() {
		                	 public   void done(List<AVObject> goodsList, AVException e) {
		                		 ImageView iv= (ImageView)findViewById(R.id.iv1);
		                	      if (e != null) {
		                	        // There was an error
		                	      } else {
		                	    	  for (AVObject goods : goodsList) {	
		                	    	  ImageLoader.getInstance().displayImage("http://ac-ak17uowd.clouddn.com/xjKo7cs5x7N3Do37KtaH83tS18ylgBaqdL72Mk6N.jpg",
				 		            			iv, options, animateFirstListener); 
		                	    	  }
		                	      }
		                	    }
		                	});
			          
		            }
		            
		        } else {
		            Log.d("失锟斤拷", "锟斤拷询锟斤拷锟斤拷: " + e.getMessage());
		        }
		    }
		});
	}
	
	/*锟斤拷锟斤拷为jazzyviewpage锟斤拷锟斤拷锟斤拷锟�*/
	private void setupJazziness(TransitionEffect effect) {
		bannerPager = (JazzyViewPager) findViewById(R.id.vpBanners);
		bannerPager.setTransitionEffect(effect);
		bannerPager.setAdapter(new BannersAdapter());
		bannerPager.setPageMargin(30);
	}

	public final class BannersAdapter extends PagerAdapter {
		
		private ImageView ivBanners;
		private Context context;
		private String url;
		
		BannersAdapter() {			
			super();
		}
		
		BannersAdapter (String url)	{
			
			BannersAdapter adapter=new BannersAdapter();
			//adapter.context = context;
			adapter.url = url;
		}
		
		@Override
		public Object instantiateItem(ViewGroup container, final int position) {
			ImageView image = new ImageView(ActivityHomePage.this);
			//image.setPadding(30, 30, 30, 30);
			int bg = Color.rgb((int) Math.floor(Math.random()*128)+64, 
					(int) Math.floor(Math.random()*128)+64,
					(int) Math.floor(Math.random()*128)+64);
			image.setBackgroundColor(bg);
			ImageLoader.getInstance().displayImage(urlList.get(position),image, options, animateFirstListener);
			container.addView(image, LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
			bannerPager.setObjectForPosition(image, position);
			return image;
		}
		@Override
		public void destroyItem(ViewGroup container, int position, Object obj) {
			container.removeView(bannerPager.findViewFromObject(position));
		}
		@Override
		public int getCount() {
			return urlList.size();
		}
		@Override
		public boolean isViewFromObject(View view, Object obj) {
			if (view instanceof OutlineContainer) {
				return ((OutlineContainer) view).getChildAt(0) == obj;
			} else {
				return view == obj;
			}
		}			
	}	
	public static class ImageLoadListener extends SimpleImageLoadingListener {

		static final List<String> displayedImages = Collections.synchronizedList(new LinkedList<String>());

		@Override
		public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
			if (loadedImage != null) {
				ImageView imageView = (ImageView) view;
				boolean firstDisplay = !displayedImages.contains(imageUri);
				if (firstDisplay) {
					FadeInBitmapDisplayer.animate(imageView, 500);
					displayedImages.add(imageUri);
				}
			}
		}
	}
	
	/**
	 * 锟斤拷锟斤拷锟斤拷时锟斤拷锟斤拷
	 */
	private void startTask() {
		// TODO Auto-generated method stub
		isTaskRun = true;
		mTimer = new Timer();
		mTask = new TimerTask() {
			@Override
			public void run() {
				if (urlList.size()>0)
				{
					pageIndex++;
					if (pageIndex==urlList.size())
						pageIndex = 0;
					mHandler.sendEmptyMessage(0);
				}
			}
		};
		mTimer.schedule(mTask, 2 * 1000, 2 * 1000);// 锟斤拷锟斤拷锟斤拷锟斤拷锟皆讹拷锟叫伙拷锟斤拷时锟戒，锟斤拷位锟角猴拷锟诫，2*1000锟斤拷示2锟斤拷
	}

	// 锟斤拷锟斤拷EmptyMessage(0)
	@SuppressLint("HandlerLeak")
	Handler mHandler = new Handler() {
		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			setCurrentItem();
		}
	};

	/**
	 * 锟斤拷锟斤拷Page锟斤拷锟叫伙拷锟竭硷拷
	 */
	private void setCurrentItem() {
		if (urlList.size()>0)
			bannerPager.setCurrentItem(pageIndex, false);// 取锟斤拷锟斤拷锟斤拷
	}

	/**
	 * 停止锟斤拷时锟斤拷锟斤拷
	 */
	private void stopTask() {
		// TODO Auto-generated method stub
		isTaskRun = false;
		mTimer.cancel();
	}

	public void onResume() {
		super.onResume();
		setCurrentItem();
		startTask();
	}
    
	@Override
	public void onPause() {
		super.onPause();
		stopTask();
	}
	
	private void initStytleSectionGrid(){				
         
		AdapterGridTradeStyle sa=new AdapterGridTradeStyle(this);
		sa.setList(tradeStyleInfoList);
        stylesSection.setAdapter(sa);
        stylesSection.setOnItemClickListener(new OnItemClickListener() 
        { 
            public void onItemClick(AdapterView<?> parent, View v, int position, long id) 
            { 
                //Toast.makeText(HomePageActivity.this, "pic" + position, Toast.LENGTH_SHORT).show(); 
            	
               Intent intent = new Intent();//"android.intent.action.MYSTORE");
              	
               switch(position)
               {
               case 0:
            	   AVObject orders = new AVObject("Orders");
            	   orders.put("payWay", "网络支付");
            	   orders.put("address", "测试地址");
            	   orders.put("customId", "55a3c317e4b0e81232606818");
            	   orders.put("phone", "12345678");
            	   orders.put("customRemark", "test remark");
            	   orders.put("consignee", "测试收货人");
            	   orders.put("deliveryWay", "送货上门");
            	   //orders.put("orderItems", "送货上门");
            	   
            	   AVCloud.setProductionMode(false);
            	   Map<String,Object> parameters = new HashMap<String, Object>();
            	   parameters.put("object", orders);
    			   AVCloud.callFunctionInBackground("beforeSave", parameters, new FunctionCallback<AVObject>() {
    			        public void done(AVObject object, AVException e) {
    			            if (e == null) {
    			              //  processResponse(object);
    			            //	object.saveInBackground();
    			            } else {
    			               // handleError();
    			            }
    			        }
    			    });
            	   orders.saveInBackground();
            	   break;
               case 1:
            	   intent.setClass(ActivityHomePage.this,ActivityIndependentStoreHome.class);
            	   intent.putExtra("mySection", myAddr.getObjectId());
            	   startActivity(intent);
            	   break;
               case 2:
            	   intent.setClass(ActivityHomePage.this,ActivityIndependentStoreHome.class);
            	   intent.putExtra("myStore", "558e1380e4b060308e3d1f51");
            	   startActivity(intent);
            	   break;
               case 3:
            	   intent.setClass(ActivityHomePage.this,ActivityIndependentStoreHome.class);
            	   intent.putExtra("mySection", myAddr.getObjectId());
            	   intent.putExtra("myStore", "558e1380e4b060308e3d1f51");
            	   startActivity(intent);
            	   break;
            	   default:
            		   break;
               }            
               
            } 
        }); 
        stylesSection.setSelector(new ColorDrawable(Color.TRANSPARENT));
	}
}
